package com.sky.aop;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {


    @Pointcut("@annotation(com.sky.annotation.AutoFill)")
    public void pc() {
    }


    @Before("pc()")
    public void before(JoinPoint joinPoint) throws Exception{
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoFill autoFill = method.getAnnotation(AutoFill.class);

        OperationType operationType = autoFill.value();

        Object[] args = joinPoint.getArgs();
        Object arg = args[0];

        Class<?> clazz = arg.getClass();

        if (operationType == OperationType.INSERT) {
            log.info("插入数据");
            Method setCreateTime = clazz.getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            setCreateTime.invoke(arg, LocalDateTime.now());
            Method setUpdateTime = clazz.getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            setUpdateTime.invoke(arg, LocalDateTime.now());
            Method setCreateUser = clazz.getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            setCreateUser.invoke(arg, BaseContext.getCurrentId());
            Method setUpdateUser = clazz.getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            setUpdateUser.invoke(arg, BaseContext.getCurrentId());


        } else if (operationType == OperationType.UPDATE) {
            log.info("更新数据");
            Method setUpdateUser = clazz.getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            setUpdateUser.invoke(arg, BaseContext.getCurrentId());
            Method setUpdateTime = clazz.getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            setUpdateTime.invoke(arg, LocalDateTime.now());
        }

    }


}
